/**
 * Copyright (c) 2010 by Kevin Bierhoff.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *    1. Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *    2. Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *    3. Neither the names of the authors nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.googlecode.syper.javasyp.prover;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.googlecode.syper.javasyp.prover.ProverResult.Status;

/**
 * @author kevin
 * @since Feb 13, 2010
 *
 */
public class SmtSolverZ3 implements Callable<Status> {

	private static final Logger log = Logger.getLogger(SmtSolverZ3.class.getName());

	private final Process z3;
	private final PrintWriter out;
	private final boolean logInout;
	private final StringBuilder z3input;
	private final StringBuilder z3output;
	private volatile String messages = null;
	private String result;
	private final Map<String, Object> model = new LinkedHashMap<String, Object>();

	SmtSolverZ3(Process z3, boolean logInout) throws IOException {
		this.z3 = z3;
		this.logInout = logInout;
		out = new PrintWriter(z3.getOutputStream());
		if (logInout) {
			z3input = new StringBuilder();
			z3output = new StringBuilder(10); // fit "unsat\n"
		} else {
			z3input = null;
			z3output = null;
		}
	}

	public void println(String line) {
		if (logInout)
			z3input.append(line).append('\n');
		out.println(line);
	}

	public Map<String, ? extends Object> getModel() {
		return model;
	}

	public String getMessages() {
		return messages;
	}

	public String getQuery() {
		return z3input == null ? null : z3input.toString();
	}

	/**
	 * Runs Z3 and returns the result, also populates {@link #getModel()}
	 * and {@link #getMessages()} (even if exception is thrown)
	 * @return Prover status
	 * @throws IOException if Z3 terminates unexpectedly or I/O problems
	 * @throws InterruptedException
	 */
	public Status call() throws IOException, InterruptedException {
		int exit;
		try {
			exit = call0();
		} catch (InterruptedException e) {
			log.log(Level.SEVERE, "solver run interrupted", e);
			z3.destroy();
			throw e;
		}
		if (exit != 0 /* unsat as expected */
				&& exit != 102 /* timeout */
				&& exit != 105 /* sat (unexpected) */
				&& exit != 112 /* unknown */) {
			// preserve all output for debugging
			if (z3output != null)
				messages = z3output.toString();
			throw new IOException("Z3 terminated unexpectedly with exit code " + exit);
		}

		if (exit == 0 && "unsat".equals(result))
			return ProverResult.Status.UNSAT;
		else if ("sat".equals(result))
			return ProverResult.Status.SAT;
		else if ("unknown".equals(result))
			return ProverResult.Status.UNDECIDED;
		else if ("timeout".equals(result))
			return ProverResult.Status.TIMEOUT;
		else
			return ProverResult.Status.OTHER;
	}

	private Integer call0() throws IOException, InterruptedException {
		// close stdin so Z3 doesn't hang waiting for input
		out.close();
		if (logInout && log.isLoggable(Level.INFO))
			log.info(z3input.toString());
		else
			System.out.println(z3input.toString());

		// process output
		final LineNumberReader in =
			new LineNumberReader(new InputStreamReader(z3.getInputStream()));
		Map<String, Object> fun = model;
		for (String more = in.readLine(); more != null; more = in.readLine()) {
			if (logInout)
				z3output.append(more).append('\n');

			more = more.trim();
			if (more.isEmpty())
				continue;
			if (more.startsWith("WARNING") || more.startsWith("ERROR")) {
				// TODO should probably force-fail on ERROR, happens anyway with exit code though
				if (messages == null)
					messages = more;
				else
					messages = messages + '\n' + more;
			} else if ("}".equals(more)) {
				// function ends
				fun = model;
			} else if (more.contains("->")) {
				String[] pair = more.split("\\s*->\\s*");
				if (pair.length >= 2) {
					if ("{".equals(pair[1])) {
						fun = new LinkedHashMap<String, Object>();
						model.put(pair[0], fun);
					} else {
						fun.put(pair[0], pair[1]);
					}
				} else {
					log.log(Level.WARNING, "Unexpected model entry: " + more);
				}
			}
			result = more;
		}
		if (logInout && log.isLoggable(Level.INFO))
			log.info(z3output.toString());
		else
			System.out.println(z3output);

		// evaluate result
		int exitCode = z3.waitFor();
		if (log.isLoggable(Level.FINE))
			log.fine("Exit code: " + exitCode);
		return exitCode;
	}

	@Override
	protected void finalize() throws Throwable {
		try {
			z3.destroy();
		} finally {
			super.finalize();
		}
	}
}
